package cn.highedu.coolshark.config;

import cn.highedu.coolshark.account.security.JwtAuthenticationFilter;
import cn.highedu.coolshark.account.security.JwtTokenAuthenticationEntryPoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Autowired
    private JwtTokenAuthenticationEntryPoint jwtTokenAuthenticationEntryPoint;

    /**
     * 声明 AuthenticationManager 对象，提供认证服务
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    /**
     * 配置HTTP请求的认证规则
     * 配置Spring Security的Filter链，以及相关的安全配置
     * @param http HTTP请求的认证规则
     * @throws Exception 异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        log.debug("配置HttpSecurity对象 {}", http.getClass().getName());
        //配置不需要认证的路径, 放过静态资源
        String[] urls = {
                "/doc.html",
                "/favicon.ico",
                "/**/*.css",
                "/**/*.js",
                "/**/*.jpg",
                "/**/*.png",
                "/swagger-resources",
                "/v2/api-docs",
                "/auth/**",
                "/error/**"
        };
        //authorizeRequests 配置路径拦截，表明路径访问所对应的权限，角色，认证信息
        http.authorizeRequests()
                .mvcMatchers(urls).permitAll()
                // 其他路径需要认证
                .anyRequest().authenticated();

                //formLogin 配置登录页面相关属性, 表单登录放过 /login 路径
                //.and().formLogin().permitAll();
        //关闭csrf
        http.csrf().disable();

        //配置跨域资源共享 (Cross-Origin Resource Sharing, CORS) 支持
        http.cors();

        // 将自定义的 JwtAuthenticationFilter 添加到 Spring Security 的过滤器链中
        // 在 UsernamePasswordAuthenticationFilter 之前添加 JwtAuthenticationFilter
        // 目的是在 UsernamePasswordAuthenticationFilter 之前执行 JwtAuthenticationFilter
        // JWT认证成功后，UsernamePasswordAuthenticationFilter 就不会执行了
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        http.exceptionHandling().authenticationEntryPoint(jwtTokenAuthenticationEntryPoint);
    }

}
